package mark.tom.gear.base.manager

import android.app.Activity
import java.util.*

/**
 * @Description: Activity Manager
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.base.manager
 * @Date: 2021/1/19
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
class ActivityManager private constructor() {
    companion object {
        val instance: ActivityManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ActivityManager()
        }
    }

    private val mActivityStack: Stack<Activity> = Stack()

    fun addActivity(activity: Activity?) {
        mActivityStack.push(activity)
    }

    fun removeActivity(activity: Activity?) {
        mActivityStack.remove(activity)
    }

    fun finishActivity(vararg cls: Class<out Activity?>) {
        for (i in mActivityStack.indices.reversed()) {
            val activity = mActivityStack[i]
            for (c in cls) {
                if (c.name == activity.javaClass.name) {
                    finishActivity(activity)
                }
            }
        }
    }

    fun finishTopActivity() {
        val pop = mActivityStack.pop()
        if (null == pop || pop.isFinishing) {
            return
        }
        pop.finish()
    }

    fun finishAllActivityByWhitelist(vararg activityWhitelist: Class<out Activity?>) {
        for (i in mActivityStack.indices.reversed()) {
            val activity = mActivityStack[i]
            for (c in activityWhitelist) {
                if (c.name == activity.javaClass.name) {
                    continue
                } else {
                    finishActivity(activity)
                }
            }
        }
    }

    fun finishAllActivity() {
        for (i in mActivityStack.indices.reversed()) {
            val activity = mActivityStack[i]
            finishActivity(activity)
        }
    }

    private fun finishActivity(activity: Activity?) {
        if (null == activity || activity.isFinishing) {
            return
        }
        activity.finish()
        mActivityStack.remove(activity)
    }

    fun getActivityStack(): Stack<Activity> {
        return mActivityStack
    }

    fun isContainsActivity(activity: Activity?): Boolean {
        return mActivityStack.contains(activity)
    }

    fun isContainsActivity(activityClass: Class<out Activity?>): Boolean {
        for (i in mActivityStack.indices.reversed()) {
            val activity = mActivityStack[i]
            if (activityClass.name == activity.javaClass.name) {
                return true
            }
        }
        return false
    }

    fun getActivityCount(): Int {
        return mActivityStack.size
    }
}